import { TokenKey ,Subject_color,Login_Url,Home_Url,Expiration_reminder, Log_endColor, Log_startColor, Err_color,Wx_AppId } from '@/utils/constant';
import type { ModalType } from '@/type/interface';
/**
 * 数字类型默认值替换
 * @param val
 * @param replace
 */
export const numberValue = (val?: number | null, replace: string | number = '--') => (isNumber(val) ? (val as number) : replace);
/**
 * @description 获取 默认获取TOKEN
 */
export const getStorage = (key: string = TokenKey) => uni.getStorageSync(key);
/**
 * @description 存储 默认是TOKEN
 */
export const setStorage = (key: string = TokenKey, data: any) => uni.setStorageSync(key, data);
/**
 * @description 清除 默认是TOEKN;
 */
export const removeStorage = (key: string = TokenKey) => uni.removeStorageSync(TokenKey);
/**
 * 
 * @param title 标题问题
 * @returns 
 * @description 动态设置uni标题
 */
export const setNavTitle = (title:string) => uni.setNavigationBarTitle({ title })
/**
 * @description 二次封装showModal
 */
export const showMoadl = (data: ModalType) => {
	const {
		title = '提示',
		content = '无',
		cancelText = '取消',
		confirmText = '确定',
		showCancel = true,
		confirmColor = '#333',
		cancelColor = Subject_color,
	} = data;
	return new Promise<boolean>((resolve, reject) => {
		uni.showModal({
			title,
			content,
			cancelText,
			confirmText,
			showCancel,
			confirmColor,
			cancelColor,
			success: (res) => {
				if (res.confirm) {
					resolve(true);
				} else {
					reject(false);
				}
			},
			fail: (err: Error) => {
				reject(err);
			},
		});
	});
};

/**
 * @description 关闭遮罩
 */
export const closeLoading = () => uni.hideLoading();

/**
 * @description 打开loading
 */
export const loading = (title: string) => uni.showLoading({ title, icon: 'none' });

/**
 * @description 消息提示
 */
export const Toast = (title: string, icon?: string | any) => uni.showToast({ title, icon: icon || 'none' });

/**
 * @description 关闭所有页面跳转
 */
export const reLaunch = (url: string) => uni.reLaunch({ url });

/**
 * @description 跳转tabBar页面
 */

export const switchTab = (url: string) => uni.switchTab({ url });

/**
 * @description   关闭当前页面，跳转到应用内的某个页面
 */

export const redirectTo = (url: string) => uni.redirectTo({ url });

/**
 * @description 保留当前页面，跳转到应用内的某个页面
 */

export const navigateTo = (url: string|any) => uni.navigateTo({ url });

/**
 * @description 返回上一页面或多级页面
 */
export const navigateBack = (index: number) => uni.navigateBack({ delta: index });

/**
 * @description 使手机发生较短时间的振动（15ms）。
 */

export const vibrateShort = () => uni.vibrateShort();

/**
 * @description 开始打印 动态颜色区分打印
 */
export const conlog = (k: any, y?: any, color?: string) => {

	console.log(
		`%c${k}%c`,
		`background-color: ${color || '#ed7ded'}; padding: 5px 10px;border-radius: 2px;color: #fff;`,
		'background-color: #ea7ded; color: #fff; padding: 7px;',
		y || ''
	);
};
export const conlogText = (k: string | number, y?: any, colorStr?: string) => {
	// #ifndef APP-PLUS
		console.log(
			`%c${k}%c`,
			`color: ${colorStr || '#333'};font-size: 12px;font-weight: bold;`,
			'background-color: #ea7ded; color: #fff; padding: 7px;',
			y || ''
		);
	// #endif
	// #ifdef APP-PLUS
		console.log(`${k}`,y);
	// #endif
	
};
/**
 * @description 开始打印
 */
export const startConlog = (y?: any, k = '开始信息：') => conlog(k, y, Log_startColor);
/**
 * @description 结束打印
 */
export const endConlog = (y?: any, k = '结束信息：') => conlog(k, y, Log_endColor);
/**
 * @description 报错打印
 */
export const ErrConlog = (y?: any, k = '报错信息：') => conlog(k, y, Err_color);
/**
 * @description 获取当前路由信息
 */
export const routeGet = () => {
	let router = getCurrentPages();
	return router[router.length - 1].route;
};
/**
 * 生成0～10000的随机数
 */
export const generateId = (): number => Math.floor(Math.random() * 10000);

/**
 * 生成随机数（0 ～ max）
 * @param max 最大值
 * @returns 随机数
 */
export const getRandomInt = (max: number) => Math.floor(Math.random() * Math.floor(max));

/**
 * @description 获取微信code
 */

export const getLoginWeixinCode = (cb: Function) => {
	// #ifdef MP-WEIXIN
	uni.login({
		success: (result) => {
			return typeof cb == "function" && cb(result);
		},
	});
	// #endif
	// #ifndef MP-WEIXIN
	Toast('非小程序平台');
	//#endif
};

/**
 * @description 预览图片
 */

export const previewImage = ( data:Array<string|object> , index:number )=>{
	uni.previewImage({
		current: data[index] as any,
		urls: data as any,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
		}
	})
}

export const formatNumber = (n:Array<any>|string|number) => {
	n = n.toString()
	return n[1] ? n : '0' + n
}
/**
 * 
 * @param number 
 * @param format 
 * @returns 当前时间 年-月-日 时:分:秒 formatTimeTwo Y-M—D h:m:s
 */
export const formatTimeTwo=(number:number, format:any)=> {
	var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
	var returnArr = [];
	var date = new Date(number);
	returnArr.push(date.getFullYear());
	returnArr.push(formatNumber(date.getMonth() + 1));
	returnArr.push(formatNumber(date.getDate()));
	returnArr.push(formatNumber(date.getHours()));
	returnArr.push(formatNumber(date.getMinutes()));
	returnArr.push(formatNumber(date.getSeconds()));
	for (var i in returnArr) {
		format = format.replace(formateArr[i], returnArr[i]);
	}
	return format;
}

/**
 * @description 脱密手机号
 */
export const encryptionPhone = (phone:string) => phone.substr(0, 3) + "****" + phone.substr(7);
/**
 * @description 脱密昵称
 */
export const encryptionName = (name:string) => name.substr(0, Math.ceil(name.length / 2)) + new Array(Math.ceil(name.length / 2)).join('*');
/**
 * @description 扫码
 */
export const scan = (cb:Function) => uni.scanCode({success:(res)=>{ cb(res) }});

/**
 * @description 判断是否有上一页 如果没有返回首页
 */
export const isbackPage = (url?:string)=>{
	let pages = getCurrentPages();
	if (pages[pages.length - 2]) {
		navigateBack(-1);
	} else {
		reLaunch(url||Home_Url);
	}
}
/**
 * @param msg 提示信息
 * @param url 跳转路径
 * @description 退出登录
 */
export const clear = (msg?:string,url?:string) =>{
	Toast(msg||Expiration_reminder);
	uni.hideLoading();
	// 清除TOKEN
	removeStorage();
	setTimeout(() => {
		redirectTo(url||Login_Url);
	}, 1000);
}

/**
 * @description 复制
 */

export const copy = (msg:string|any) => uni.setClipboardData({data:msg});


/**
 * @description 拨打电话
 */
export const makePhoneCall = (msg:string)=> uni.makePhoneCall({phoneNumber:msg});

export const navigateToVib = (url:string) =>{
	navigateTo(url);
	uni.vibrateShort();
}
/**
 * @description 跳转小程序
 */
export const navigateToMiniProgramWx = (appId=Wx_AppId,vib=true)=>{
	try {
		if(vib) uni.vibrateShort();
		uni.navigateToMiniProgram({appId,fail(e){
			
		}})
	} catch(err){
		
	}
}